package com.ncr.travel.appmgr.service.mapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.deser.StdDeserializer;
import org.codehaus.jackson.node.ObjectNode;

import com.ncr.travel.appmgr.model.ErrorTextJson;
import com.ncr.travel.appmgr.model.TextJson;
import com.ncr.travel.appmgr.model.TextEntryJson;

public class TextDeserializer extends StdDeserializer<TextJson> {
	private Map<String, Class<? extends TextJson>> registry = new HashMap<String, Class<? extends TextJson>>();

	public TextDeserializer() {
		super(TextJson.class);
		registry.put("value", TextEntryJson.class);
		registry.put("message", ErrorTextJson.class);
	}

	@Override
	public TextJson deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectMapper mapper = (ObjectMapper) jp.getCodec();

		ObjectNode root = (ObjectNode) mapper.readTree(jp);
		Class<? extends TextJson> textClass = null;
		Iterator<Entry<String, JsonNode>> elementsIterator = root.getFields();
		while (elementsIterator.hasNext()) {
			Entry<String, JsonNode> element = elementsIterator.next();
			String name = element.getKey();
			if (registry.containsKey(name)) {
				textClass = registry.get(name);
				break;
			}
		}
		if (textClass == null) {
			return null;
		}
		return mapper.readValue(root, textClass);
	}
}
